<?php
/**
 * CreateTime: 2023/3/30 16:25
 */

namespace App\Service\MeCaseSerice;

use App\Consts\MeClientConsts\MeClientConsts;
use App\Func\MeLawCaseFunc;
use App\Models\File\FileModel;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use Illuminate\Support\Facades\DB;
use function Sodium\add;

class ImportLawCase
{
    public function import($data){

    }


    function pkcs7Unpadding($data)
    {
        $padding = ord(substr($data, -1));
        if ($padding > strlen($data)) {
            return false;
        }
        if (substr($data, -1 * $padding) !== str_repeat(chr($padding), $padding)) {
            return false;
        }
        return substr($data, 0, -1 * $padding);
    }

    function pkcs7Padding($data, $blockSize)
    {
        $padding = $blockSize - (strlen($data) % $blockSize);
        // 这里的填充必须是15 自定义来填充
        return $data . str_repeat(chr(15), $padding);
    }

    /**
     * 首先使用AES加密以后base64在使用urlEncode
     * @param $url
     */
    public function urlImportEncode($url){
        $key = '0123456789abcdef'; // 密钥必须是 16、24 或 32 个字符长度
        $data = $url;
        $key = openssl_encrypt($this->pkcs7Padding($data,16), 'AES-128-CBC', $key, OPENSSL_RAW_DATA,$key);
        $str = base64_encode($key);
        return urlencode($str);
    }

    public function urlImportDecode($str){
        $key = '0123456789abcdef'; // 密钥必须是 16、24 或 32 个字符长度
        $data = base64_decode(urldecode($str)); // $encrypted 是加密后的字符串
        $data = openssl_decrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $key);
        $data = $this->pkcs7Unpadding($data); // pkcs7Unpadding() 是解密后的数据去掉填充的函数
        dd($data);
    }

    // 按照委托方id去处理数组
    public function disposeData($data,$count){
        $uuid = $data['uuid'];
        switch ($uuid){
            // 如果当前用户为玖富 则调用玖富专属的业务处理方法
            case MeClientConsts::CLIENT_UUID_9F:
                 $this->dispose9fCase($data,$count);
                 break;
            case MeClientConsts::CLIENT_UUID_KZ_9F:
                $this->disposeKz9fCase($data,$count);
                break;
        }
    }

    /**
     * 处理玖富地导入数据
     */
    private function dispose9fCase($data,$count){
        echo "开始进行数据导入\n";
        $clientId = $data['clientId'];
        $ownerId = $data['ownerId'];
        // 导入的数据处理 去掉所有的""
        if($data['isHeader'] == true){
            return false;
        }
        $data = $data['value'];
        foreach($data as $key=> $value){
            $data[$key] = str_replace(["\"","年","月","日"],["","-","-",""],$value);
        }
        $custom = [
            '外部工单号' => $data[0],
            '合同签订日(必填)'  => $data[10],
            '逾期利息起算日(必填)'  => $data[13],
            '逾期年利率(必填)'  => $data[16],
            '最后一期还款日(必填)' => $data[18],
            '实际还款金额(必填)' => $data[19],
            '借款年利率' => $data[2],
            '合同金额' => $data[22],
            '产品名称' => $data[23],
            '逾期本金' => $data[24],
            '逾期利息' => $data[25],
            '红包金额' => $data[27],
            '案件号' => $data[28],
            '收款银行卡' => $data[29],
            '邮箱' => $data[30],
            '剩余本金' => $data[31],
            '性别' => $data[5],
            '民族(必填)' => $data[6],
            '邮寄地址/送达地址(必填' => $data[7],
            '利息暂计日(必填)' => $data[9]
        ];
        $customStr = json_encode($custom,256);
        $res = [
            'client_id' => $clientId,
            'law_case_code' => MeLawCaseFunc::getLawCaseUnionCode($clientId,$count),
            'owner_id' => $ownerId,
            'loans_contract_code' => $data[1],
            # 贷款日期(必填)
            'loans_time' => date("Y-m-d h:i:s",strtotime($data[10])),
            # 逾期日期(必填)
            'loans_overdue_time'=> date("Y-m-d h:i:s",strtotime($data[12])),
            # 放贷日期
            'loans_start_time'=> date("Y-m-d h:i:s",strtotime($data[14])),
            # 贷款金额
            'loans_money' => $data[15],
            # 贷款期限(必填)  
            'loans_periods_number' => $data[17],
            # 实还本金
            'loans_input_money_principal' => $data[20],
            # 实还利息
            'loans_input_money_interest' => $data[21],
            # 身份证地址
            'respondent_house_address' =>  $data[26],
            # 姓名
            'respondent_name' => $data[3],
            # 身份证号
            'respondent_id_card' => $data[4],
            # 手机号码(必填)
            'respondent_phone_ids' => "",
            # 自定义字段
            'law_case_custom' => $customStr
        ];

        static $flag = true;
        static $meModel = "";
        static $mePhone = "";
        static $db = "";
        if($flag){
            $meModel = new MeLawCase();
            $mePhone = new MeLawCasePhoneModel();
            $flag = false;
            $db = new DB();
        }
        $db::beginTransaction();
        try {
            // 校验手机号是否存在 如果已经存在则不进行添加
            $isExists = $mePhone->isExistByCondition(
                [
                    'phone_number' => $data[8]
                ]
            );
            if(!$isExists){
                // 加入号码表
                $phoneId = $mePhone->add([
                    'phone_number' => $data[8],
                    'phone_status' => 1,
                    'is_law_case_main_phone' => 1,
                    'status' => 1,
                ]);
                $res['respondent_phone_ids'] = $phoneId;
                $res['main_respondent_phone_id'] = $phoneId;
            }

            $id = $meModel->add($res);
            echo "结束数据导入 导入数据ID为".$id."\n";
            $db::commit();
        }catch (\Exception $exception){
            $db::rollBack();
            echo "sql执行异常".$exception->getMessage();
        }
    }

    private function disposeKz9fCase($data,$count){
        echo "开始进行数据导入\n";
        $clientId = $data['clientId'];
        $ownerId = $data['ownerId'];
        // 导入的数据处理 去掉所有的""
        if($data['isHeader'] == true){
            return false;
        }
        $data = $data['value'];
        foreach($data as $key=> $value){
            $data[$key] = str_replace(["\"","年","月","日"],["","-","-",""],$value);
        }
        $custom = [
            '案件号' => $data[0],
            '三方号码' => $data[3],
            '总逾期本息' => $data[4],
            '最长逾期天数'  => $data[5],
            '邮箱'  => $data[6],
            '已还总金额'  => $data[7],
            '产品类型'  => $data[8],
            '央行待上报工单号'  => $data[9],
            '对公还款账户'  => $data[11],
            '对公账户名'  => $data[12],
            '对公账户户行'  => $data[13],
            '应还总金额'  => $data[14],
            '收货人地址'  => $data[16],
            '居住地址'  => $data[17],
            '计算本金'  => $data[18],
            '1档结清金额'  => $data[19],
            '2档结清金额'  => $data[20],
            '3档结清金额'  => $data[21],
            '4档结清金额'  => $data[22],
            '低龄低减'  => $data[23],
            '低龄高减'  => $data[24],
            '高龄低减'  => $data[25],
            '高龄高减'  => $data[26],
            '低龄低减总和'  => $data[27],
            '低龄高减总和'  => $data[28],
            '高龄低减总和'  => $data[29],
            '高龄高减总和'  => $data[30],
            '分按日期'  => $data[31],
            '系统分按日期'  => $data[32],
            '催告人'  => $data[33],
        ];
        $customStr = json_encode($custom,256);
        $res = [
            'client_id' => $clientId,
            'law_case_code' => MeLawCaseFunc::getLawCaseUnionCode($clientId,$count),
            'owner_id' => $ownerId,
            # 身份证地址
            'respondent_house_address' =>  $data[15],
            # 姓名
            'respondent_name' => $data[1],
            # 身份证号
            'respondent_id_card' => $data[2],
            # 自定义字段
            'law_case_custom' => $customStr
        ];

        static $flag = true;
        static $meModel = "";
        static $mePhone = "";
        static $db = "";
        if($flag){
            $meModel = new MeLawCase();
            $mePhone = new MeLawCasePhoneModel();
            $flag = false;
            $db = new DB();
        }
        $db::beginTransaction();
        try {
            // 校验手机号是否存在 如果已经存在则不进行添加
            $isExists = $mePhone->isExistByCondition(
                [
                    'phone_number' => $data[8]
                ]
            );
            if(!$isExists){
                // 加入号码表
                $phoneId = $mePhone->add([
                    'phone_number' => $data[8],
                    'phone_status' => 1,
                    'is_law_case_main_phone' => 1,
                    'status' => 1,
                ]);
                $res['respondent_phone_ids'] = $phoneId;
                $res['main_respondent_phone_id'] = $phoneId;
            }

            $id = $meModel->add($res);
            echo "结束数据导入 导入数据ID为".$id."\n";
            $db::commit();
        }catch (\Exception $exception){
            $db::rollBack();
            echo "sql执行异常".$exception->getMessage();
        }
    }




}